//
//  ACTextField.swift
//  UITextField自定义leftView
//
//  Created by 李煜 on 2023/3/14.
//https://blog.csdn.net/Morris_/article/details/126262325

import UIKit

class ACTextField: UITextField {

  /// 设置icon
  var icon: UIImage? {
    set {
      imageView?.image = newValue
    }
    get {
      return imageView?.image
    }
  }

  // MARK: - 私有
  private var imageView: UIImageView?

  override init(frame: CGRect) {
    super.init(frame: frame)
    self.imageView = UIImageView(frame: CGRect(x: 8, y: 8, width: self.frame.size.height - 16, height: self.frame.size.height - 16))
    self.leftView = imageView
    self.leftViewMode = .always
  }

  @available(*, unavailable)
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    if let view = leftView {
      return view.frame
    }
    return .zero
  }

  override func editingRect(forBounds bounds: CGRect) -> CGRect {
    if let view = leftView {
      return CGRect(x: view.frame.maxX + 8, y: bounds.minY, width: bounds.width - view.frame.maxX - view.frame.minX, height: bounds.height)
    }
    return CGRect(x: bounds.minX + 8, y: bounds.minY, width: bounds.width - 8, height: bounds.height)
//    return super.editingRect(forBounds: bounds)
  }
}
